package com.simple.gateway.pay.strategy;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;
import lombok.SneakyThrows;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;

/**
 * @description: yasud
 * @author: Mr.Kang
 * @create: 2021-04-10 11:44
 **/
public abstract class AbstractSignStrategy<R> implements SignStrategy<R> {

    /**
     *
     * @param uri
     * @return
     */
    abstract void getUri(String uri);
    abstract void getMid(String mid);
    abstract void getTs(String ts);
    abstract void getVersion(String version);
    /**
     *
     * @param body
     * @return
     */
    abstract R convertRequest(String body);


    @SneakyThrows
    @Override
    public R requestSign(HttpServletRequest request) {
        getUri(request.getRequestURI());
        getMid(request.getHeader("mid"));
        getTs(request.getHeader("ts"));
        getVersion(request.getHeader("version"));
        ServletInputStream inputStream = request.getInputStream();
        List<String> lines = CharStreams.readLines(new InputStreamReader(inputStream, Charsets.UTF_8));
        String reduce = lines.stream().reduce("", (v, vv) -> v += vv);
        return convertRequest(reduce);
    }

    abstract R converResponse(Map<String,Object> dataMap, Long ts);

    @SneakyThrows
    @Override
    public R responseSign(Map<String,Object> dataMap, HttpServletRequest request, Long ts) {
        getUri(request.getRequestURI());
        getVersion(request.getHeader("version"));
        getMid(request.getHeader("mid"));
        getTs(String.valueOf(ts));
        return converResponse(dataMap,ts);
    }
}
